# coding=utf-8

import logging
import re
import socket
import threading
import time
import os
from .Email import *
from .Config import *


class Monitor(threading.Thread):
    hostname = socket.gethostname()
    localIP = socket.gethostbyname(hostname)
    loopTime = 0
    preEmailTime = 0
    preErrObj = []

    email = Email()
    config = Config()

    def setConfig(self, config):
        self.config = config
        self.email.setConfig(self.config)

    def run(self):
        logging.info(self.config.getAppName() + "monitor log start")
        self.email.send_mail(self.config.getAppName() + " start", self.config.getAppName() + " start")
        while True:
            time.sleep(self.loopTime)
            self.loopTime = 60
            hour = time.localtime(time.time())[3]
            minute = time.localtime(time.time())[4]
            # every day clear 
            if hour == 0 and minute == 0:
                #self.preErrObj = None
                logging.info("monitor loop:" + time.strftime("%Y%m%d", time.localtime(time.time())))
            #logname = self.config.getLogName()
            #if logname.find("%Y") or logname.find("%m") or logname.find("%d"):
            #    logname = time.strftime(logname, time.localtime(time.time()))
            #logtext = open(self.config.getLogDir() + logname, 'rb').read()
            #regstr = self.config.getLogErrorRe()
            #it = re.finditer(regstr, logtext)
            #if it is None:
            #    continue
            #lastobj = None
            #for i in it:
            #    lastobj = i
            # same error
            fileList = os.listdir(self.config.getLogDir())
            fileList.sort()
            #logging.info(fileList)
            lastobj = []
            for file in fileList:
                if re.match(r'.*\.log', file):
                    lastobj.append(file)
            
            #logging.info(lastobj)
            #logging.info(self.preErrObj)
            if lastobj == self.preErrObj:
                continue
            self.preErrObj = lastobj
            # min 6h send one email
            if time.time() - self.preEmailTime < 6 * 60 * 60:
                logging.info("pre email is less than 6h. skip send email!!!")
                continue
            self.preEmailTime = time.time()
            content = self.hostname + " " + self.localIP + " error info:".join(lastobj)
            self.email.send_mail(self.config.getAppName() + " error log", content)
            logging.error(content + "\r\n")
